package edu.xjtu.jih.selfDemands;

import edu.xjtu.jih.common.Result;
import edu.xjtu.jih.common.Utils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet( {"/item/itemList",
             "/item/itemDoAdd",
              "/item/itemDoUpd",
                "/item/itemDoDel"


})
public class SelfDemandsAPI extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        SelfDemandsService selfDemandsService=new SelfDemandsService();
        request.setCharacterEncoding("UTF-8");
        String path = request.getServletPath();

        /*if("/item/itemDoAdd".equals(path)){

            SelfDemandsDto dto = Utils.getBeanFromRequest(SelfDemandsDto.class,request);
            //System.out.println("dto:"+dto);
            selfDemandsService.addItem(dto);

            Utils.outJson(response, Result.success());

        }*/
        if("/item/itemDoUpd".equals(path)){

            try {
                SelfDemandsDto dto = Utils.getBeanFromRequest(SelfDemandsDto.class,request);
                //System.out.println("dto:"+dto);
                selfDemandsService.updateSelfDemandsInfo(dto);

                Utils.outJson(response, Result.success());
            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            }

        }
        else if("/item/itemDoDel".equals(path)){

            try {
                SelfDemandsDto dto = Utils.getBeanFromRequest(SelfDemandsDto.class,request);
                //System.out.println("dto:"+dto);
                selfDemandsService.deleteSelfDemandsInfo(dto);

                Utils.outJson(response, Result.success());
            } catch (Exception e) {
                e.printStackTrace();
                Utils.outJson(response, Result.fail(Result.ERR_CODE_BUSINESS, e.getMessage()));
            }

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SelfDemandsService selfDemandsService=new SelfDemandsService();
        List<SelfDemands> selfDemandsList=selfDemandsService.getSelfDemandsList();

        //通过视图形成json
       // Utils.outJson(response,itemList);
        Utils.outResult(response, Result.success(selfDemandsList));

    }
}
